package com.whq.mvc.mq;

import com.whq.mvc.dao.ItemStockDOMapper;
import com.whq.mvc.resp.BusinessException;
import com.whq.mvc.utils.JsonUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Map;

@Component
@RabbitListener(queues = "queue_item_stock")
public class MqConsumer {

    @Autowired
    private ItemStockDOMapper itemStockDOMapper;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @RabbitHandler
    public void process(Map<String,Object> message){
        transactionTemplate.execute(status -> {
            try {
                System.out.printf("开始接收到消息-----%s\n", JsonUtils.toJSON(message));
            } catch (BusinessException e) {
                e.printStackTrace();
            }
            Integer itemId = (Integer) message.get("itemId");
            Integer amount = (Integer) message.get("amount");
            itemStockDOMapper.decreaseStock(itemId,amount);
            return true;
        });
    }
}
